package com.wss.lsl.test.driven.scoketio.tcp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

public class HelloClientIo {

	private static final String UTF8 = "UTF-8";
	private static final Random r = new Random();

	@SuppressWarnings("resource")
	public static void main(String[] args) throws UnknownHostException,
			IOException {
		final Socket s = new Socket("localhost", 8888);
		final OutputStream os = s.getOutputStream();
		final InputStream is = s.getInputStream();

		// 输入：把内容推送到服务端
		new Thread(new Runnable() {

			@Override
			public void run() {
				BufferedWriter bw = null;
				try {
					bw = new BufferedWriter(new OutputStreamWriter(os, UTF8));
					boolean f = true;
					int count = 0;
					String content = null;
					while (f) {
						count++;
						// readLine()将阻塞，等待客户端的输入
						if (r.nextInt(100) < 50) {
							content = "中文测试" + count;
						} else {
							content = "english test" + count;
						}
						System.out.println("send:" + content);
						content += "\n"; // 回车，远程服务器才会开始读取内容
						bw.write(content);
						bw.flush();
						TimeUnit.SECONDS.sleep(1);
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						if (bw != null) {
							bw.close();
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();

		// 输出：从服务端读取内容
		new Thread(new Runnable() {

			@Override
			public void run() {
				BufferedReader br = null;
				try {
					br = new BufferedReader(new InputStreamReader(is, UTF8));
					String content = null;
					boolean f = true;
					while ((content = br.readLine()) != null && f) {
						// readLine()将阻塞，等待客户端的输入
						System.out.println("received:" + content);
						if ("bye".equals(content)) {
							f = false;
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						if (br != null) {
							br.close();
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
}
